#include <iostream>
#include <unordered_map>
#include <functional>
#include <memory>

// 定义一个接口，代表Bean
class Bean {
public:
    virtual void print() = 0;
    virtual void show() = 0;
    virtual ~Bean() {}
};

// 实现一个具体的Bean类
class MyBean : public Bean {
public:
    void print() override {
        std::cout << "Hello, I am a Bean!" << std::endl;
    }
    void show() override {
        std::cout << "show, I am a Bean!" << std::endl;
    }
};

// 实现一个具体的LogBean类
class LogerBean : public Bean {
public:
    void print() override {
        std::cout << "Hello, I am a Logger Bean!" << std::endl;
    }
    void show() override {
        std::cout << "show, I am a Logger Bean!" << std::endl;
    }
};


// 定义BeanFactory类
class BeanFactory {
private:
    std::unordered_map<std::string, std::function<std::shared_ptr<Bean>()>> beanMap;

public:
    // 注册Bean的创建函数
    void registerBean(const std::string& beanName, std::function<std::shared_ptr<Bean>()> creator) {
        beanMap[beanName] = creator;
    }

    // 获取Bean实例
    std::shared_ptr<Bean> getBean(const std::string& beanName) {
        if (beanMap.find(beanName) != beanMap.end()) {
            return beanMap[beanName]();
        } else {
            return nullptr;
        }
    }

    ~BeanFactory() {
        for (auto& entry : beanMap) {
            entry.second = nullptr;
        }
    }

    int showBean() {
        for(auto i: beanMap) {
            std::cout << i.first << ":" << i.second() << std::endl;
        }
        return 0;
    }

};

int main() {
    // 创建一个BeanFactory实例
    BeanFactory beanFactory;

    // 注册一个名为"myBean"的Bean
    beanFactory.registerBean("myBean", []() {
        return std::make_shared<MyBean>();
    });
    // 注册一个名为"logerBean"的Bean
    beanFactory.registerBean("loggerBean", []() {
        return std::make_shared<LogerBean>();
    });


    // 获取名为"myBean"的Bean实例并调用print方法
    std::shared_ptr<Bean> bean = beanFactory.getBean("myBean");
    if (bean) {
        bean->print();
        bean->show();
    } else {
        std::cout << "Bean not found!" << std::endl;
    }

    // 获取名为"logerBean"的Bean实例并调用print方法
    std::shared_ptr<Bean> bean2 = beanFactory.getBean("loggerBean");
    if (bean2) {
        bean2->print();
        bean2->show();
    } else {
        std::cout << "Logger Bean not found!" << std::endl;
    }

    beanFactory.showBean();

    return 0;
}